package com.tidc.searabbit.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.tidc.seaservermodel.config.RedisConfig;
import com.tidc.seaservermodel.entity.RabbitMessageLog;
import com.tidc.seaservermodel.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020/9/27 20:48
 * @description：
 * @modified By：
 * @version:
 */
@Aspect
@Component
@Slf4j
public class ConsumerAspect {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ObjectMapper objectMapper;


    @Pointcut("execution(* com.tidc.searabbit.consumer.MessageConsumer.*(com.tidc.seaservermodel.entity.RabbitMessageLog,com.rabbitmq.client.Channel,org.springframework.amqp.core.Message))")
    private void preventDuplicate() {
    }





    @AfterThrowing(value = "preventDuplicate()", throwing = "ex")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable ex) throws IOException {
        Object[] args = joinPoint.getArgs();
        Channel channel = (Channel) args[1];
        Message message = (Message) args[2];
//        返回
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
    }

    @Around(value = "preventDuplicate()")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        RabbitMessageLog rabbitMessageLog = (RabbitMessageLog) args[0];
        Channel channel = (Channel) args[1];
        Message message = (Message) args[2];
        channel.basicQos(1);//开启手动应答
        if(redisUtil.hasKey(RedisConfig.REPETITION_RABBIT + rabbitMessageLog.getMsgId())){
            log.info("重试");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);//应答
            return null;
        }
        Object res = pjp.proceed();
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);//应答
        redisUtil.set(RedisConfig.REPETITION_RABBIT + rabbitMessageLog.getMsgId(),"1");
        return res;
    }

}
